﻿using Microsoft.VisualBasic.CompilerServices;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Program09
{
    class Program
    {
        /// <summary>
        /// 利用序列化存储对象到文件流中
        /// </summary>
        static void Main(string[] args)
        {
            //var p = new Person()
            //{
            //    No = "001",
            //    Name = "老王",
            //    Age = 19
            //};
            ////把对象存放到文件中
            //using (FileStream fsWrite = new FileStream("person.db", FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    //读对象内容，转化为二进制，序列化
            //    var buffer = new BinaryFormatter();
            //    buffer.Serialize(fsWrite, p);
            //}
            //Console.WriteLine("序列化成功，存储成功！");

            //从文件中读出对象的内容
            Person p;
            using (FileStream fsRead = new FileStream("person.db", FileMode.OpenOrCreate, FileAccess.Read))
            {
                var buffer = new BinaryFormatter();
                p = (Person)buffer.Deserialize(fsRead);
            }
            Console.WriteLine("工号：{0} 姓名：{1} 年龄：{2}", p.No, p.Name, p.Age);

        }
        //定义可序列化的类
        [Serializable]
        public class Person
        {
            //工号
            public string No { get; set; }
            //姓名
            public string Name { get; set; }
            //年龄
            public int Age { get; set; }
        }
    }
}
